import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author 雷明浩
 * @date 2025/5/29 15:08
 */
public class InorderTraversal {
    // leetcode 二叉树的中序遍历
    // https://leetcode.cn/problems/binary-tree-inorder-traversal/?envType=study-plan-v2&envId=top-100-liked

    private List<Integer> ret;

    /**
     * 递归的方式实现二叉树的中序遍历
     * @param root
     * @return
     */
    public List<Integer> inorderTraversal1(TreeNode root) {
        ret = new ArrayList<>();
        inorderTraversalChild(root);
        return ret;
    }

    private void inorderTraversalChild(TreeNode root) {
        if (root == null) {
            return;
        }
        inorderTraversalChild(root.left);
        ret.add(root.val);
        inorderTraversalChild(root.right);
    }

    /**
     * 非递归的方式实现二叉树的中序遍历
     * @param root
     * @return
     */
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        while (!stack.isEmpty() || root != null) {
            while (root != null) {
                stack.add(root);
                root = root.left;
            }
            TreeNode node = stack.pop();
            ret.add(node.val);
            root = node.right;
        }
        return ret;
    }
}